package com.example.maybeaccount;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.MemoryFile;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.maybeaccount.Entry.Entrance;
import com.example.maybeaccount.Mode.Item;
import com.example.maybeaccount.Mode.ItemAdapter;
import com.example.maybeaccount.Mode.ItemManager;
import com.example.maybeaccount.Mode.MyTimer;
import com.example.maybeaccount.Mode.SpacesItemDecoration;
import com.example.maybeaccount.Mode.SqliteDB;
import com.example.maybeaccount.Mode.MemberItemAdapter;
import com.example.maybeaccount.datepicker.CustomDatePicker;
import com.example.maybeaccount.datepicker.DateFormatUtils;

import java.util.ArrayList;
import java.util.Calendar;

/** 成员支出条形图展示活动
 *  注：我们认为收入不需要分成员，我们有能力实现，但认为它不符合实际逻辑
 */
public class MemberChartActivity extends AppCompatActivity {
    private boolean isTop;
    int mode = MemberItemAdapter.MODE_EXPEND;
    int firstFlag = 0;
    private TextView startTime;
    private TextView endTime;
    private Calendar startCalendar = Calendar.getInstance();
    private Calendar endCalendar = Calendar.getInstance();

    private CustomDatePicker mTimerPicker1;
    private CustomDatePicker mTimerPicker2;
    public ItemManager itemManager;
    private RecyclerView recyclerView;
    private ArrayList<Item> itemList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBroadcast();
        setContentView(R.layout.member_chart);

        recyclerView = findViewById(R.id.recycler_view);
        startTime = findViewById(R.id.start_time);
        endTime = findViewById(R.id.end_time);

        //初始化时间选择
        initTimerPicker();
        startCalendar = MyTimer.getTimeByString(startTime.getText().toString());
        endCalendar = MyTimer.getTimeByString(endTime.getText().toString());

        //返回按钮
        ImageButton butChartBack = (ImageButton)findViewById(R.id.button_chart_back);
        butChartBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent= new Intent(MemberChartActivity.this, Chart.class);
                intent.putExtra("member",1);
                startActivity(intent);
            }
        });

        //设置图表时间
        initTimerPicker();
        startTime.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                mTimerPicker1.show(startTime.getText().toString());

            }
        });

        endTime.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                mTimerPicker2.show(endTime.getText().toString());

            }
        });

        initVisualData();

    }

    /**
     * 后台唤醒后进入密码界面
     */
    @Override
    protected void onResume(){
        super.onResume();
        isTop = true;
        if(firstFlag == 1){
            firstFlag = 0;
            Intent intent = new Intent(MemberChartActivity.this, Entrance.class);
            intent.putExtra("resume","Member");
            startActivity(intent);
        }else{
            firstFlag = 0;
        }
    }

    @Override
    protected void onPause(){
        super.onPause();
        isTop = false;
    }

    /**
     * 重写返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            //Intent intent= new Intent(MemberChartActivity.this, Chart.class);
            //intent.putExtra("member",1);
            //startActivity(intent);
            finish();
        }
        return true;
    }

    private boolean initVisualData(){
        //获取所有账单
        itemList = SqliteDB.getInstance(getApplicationContext()).getAllItem();
        if(itemList.isEmpty()){
            return false;
        }else{
            itemManager = new ItemManager();
            itemManager.setItem(itemList);
            itemManager.chooseAccount("全部账户");

            LinearLayoutManager layoutManager= new LinearLayoutManager(this);
            recyclerView.setLayoutManager(layoutManager);
            setRecyclerView(mode);
            //设置各个item之间的间隔
            int space = 8;
            recyclerView.addItemDecoration(new SpacesItemDecoration(space));
            return true;
        }
    }

    /**
     * 控制recyclerView显示的模式
     * @param mode
     */
    private void setRecyclerView(int mode){
        if(itemManager != null){
            MemberItemAdapter memberItemAdapter = new MemberItemAdapter(itemManager.getMemberItemList(startCalendar,endCalendar),mode,this);
            recyclerView.setAdapter(memberItemAdapter);
        }

    }

    private void initTimerPicker() {
        String beginTime = "2000-1-1 00:00";
        String stopTime = DateFormatUtils.long2Str(System.currentTimeMillis(), true);

        startTime.setText(beginTime);

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mTimerPicker1 = new CustomDatePicker(MemberChartActivity.this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                startTime.setText(DateFormatUtils.long2Str(timestamp, true));
                /** 此处为更新RV */
                startCalendar = MyTimer.getTimeByString(startTime.getText().toString());
                setRecyclerView(mode);

            }
        }, beginTime, stopTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker1.setCancelable(true);
        // 显示时和分
        mTimerPicker1.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker1.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker1.setCanShowAnim(true);

        this.endTime.setText(stopTime);
        String FinalTime = "2030-10-17 18:00";

        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        mTimerPicker2 = new CustomDatePicker(MemberChartActivity.this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                endTime.setText(DateFormatUtils.long2Str(timestamp, true));
                /** 此处为更新RV */
                endCalendar = MyTimer.getTimeByString(endTime.getText().toString());
                setRecyclerView(mode);

            }
        }, beginTime, stopTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker2.setCancelable(true);
        // 显示时和分
        mTimerPicker2.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker2.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker2.setCanShowAnim(true);
    }

    /** 广播监听home和menu */
    class InnerRecevier extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {

                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

                if (reason != null) {

                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY) && isTop) {
                        // "Home键被监听"
                        firstFlag = 1;

                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS) && isTop) {
                        //"多任务键被监听"
                        firstFlag = 1;

                    }
                }
            }
        }
    }

    private void initBroadcast(){
        /** 广播 */
        this.getWindow().setFlags(0x80000000,0x80000000);
        //创建广播
        InnerRecevier innerReceiver = new InnerRecevier();
        //动态注册广播
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        //启动广播
        registerReceiver(innerReceiver, intentFilter);
    }

}
